#include "my_serial.h"
#define DEBUG 0
// 定义帧头和帧尾长
const byte FRAME_HEAD_LENGTH = 2;
const byte FRAME_TAIL_LENGTH = 1;
const byte FRAME_DATA_LENGTH = 67;
const byte FRAME_TOTAL_LENGTH = FRAME_HEAD_LENGTH + FRAME_DATA_LENGTH + FRAME_TAIL_LENGTH;
byte SendBUFF[70]={0};

// 定义帧头
const byte frameHead[FRAME_HEAD_LENGTH] = {0x7f, 0xaa}; // 假设帧头只有0x7f, 0xaa，第三个字节作为同步字节在数据接收中检

// 缓冲
byte buffer[FRAME_TOTAL_LENGTH];
byte receivedBytes = 0;
unsigned long lastReceiveTime = 0;

// 计算帧尾校验和的函数
byte calculateChecksum(byte* data, byte length) {
  byte checksum = 0;
  for (byte i = 0; i < length; i++) {
    checksum += data[i];
  }
  return checksum;
}

void MY_Serial::setup()
{
	Serial.begin(115200); // 初始化串口通信
	SendBUFF[0]=0x7f;
	SendBUFF[1]=0xaa;
	SendBUFF[2]=0xa3;
	SendBUFF[69]=0xa3;
#if DEBUG
  Serial.println("baudrate 115200!");
#endif
}
void MY_Serial::send_uart()
{
#if DEBUG
 Serial.println("send_uart");
#endif
	Serial.write(SendBUFF,70);

}
void MY_Serial::rev_uart()
{
unsigned long currentTime = millis();
  byte temp;
  // 尝试从串口读取数
  while (Serial.available() > 0 && receivedBytes < FRAME_TOTAL_LENGTH) {
    // 检查上一个数据帧接收是否超时80毫秒周期
  if (currentTime - lastReceiveTime >= 80) {
    receivedBytes = 0; // 重置接收到的字节
    }
    temp= Serial.read();
    buffer[receivedBytes++] = temp;
#if DEBUG
    Serial.write(temp);
#endif
    // 检查帧头（假设第三个字节为同步字节，用于验证帧头完整性）
    if (receivedBytes == FRAME_HEAD_LENGTH) {
      if (buffer[0] != frameHead[0] || buffer[1] != frameHead[1]) {
        receivedBytes = 0; // 帧头不匹配，重置接收到的字节
#if DEBUG
        Serial.print("CheckHead error!");
        Serial.print(buffer[0],HEX);
        Serial.print(buffer[1],HEX);
#endif
        return;
      }
    }
    lastReceiveTime = currentTime; // 更新最后接收时
  }

  // 如果接收完一个完整的数据
  if (receivedBytes == FRAME_TOTAL_LENGTH) {
    // 计算帧尾校验
    byte expectedChecksum = calculateChecksum(&buffer[2], FRAME_DATA_LENGTH);
    byte receivedChecksum = buffer[FRAME_TOTAL_LENGTH - 1];

    // 验证帧尾校验
    if (expectedChecksum == receivedChecksum) {
		cnt=buffer[68];
    check=buffer[3];
#if DEBUG
      // 校验和正确，处理数据帧（此处仅打印数据长度作为示例）
      Serial.println("Frame received correctly");
      timcheck = 0;//至此收到了完整正确的弹计数据
#endif
      // 可以在此处添加处理数据的代码
    } else {
#if DEBUG
      // 校验和不正确，丢弃数据帧
      Serial.println("Checksum error!");
      Serial.printf("%X!=%X",expectedChecksum,receivedChecksum);
#endif
    }

    // 重置接收到的字节数，准备接收下一个数据帧
    receivedBytes = 0;
  }
}


